package tony.minio.oss

import io.minio.MinioClient
import io.minio.PutObjectArgs
import java.io.InputStream
import org.springframework.util.unit.DataSize
import tony.core.oss.IOssService
import tony.core.utils.sanitizedPath
import tony.minio.oss.autoconfigure.MinioOssProperties

/**
 * MinioOssService is
 * @author tangli
 * @date 2025/10/09 16:58
 */
internal class MinioOssService(
    private val minioClient: MinioClient,
    private val minioOssProperties: MinioOssProperties,
) : IOssService {
    override fun putObject(
        path: String,
        inputStream: InputStream,
    ): String =
        minioClient.run {
            val sanitizedPath = sanitizedPath(path).removePrefix("/")
            putObject(
                PutObjectArgs
                    .builder()
                    .bucket(minioOssProperties.bucketName)
                    .`object`(sanitizedPath)
                    .stream(inputStream, -1, DataSize.ofMegabytes(5).toBytes())
                    .build()
            )
            val endpoint =
                if (minioOssProperties.endpoint.startsWith("http")) {
                    minioOssProperties.endpoint
                } else {
                    "https://${minioOssProperties.endpoint}"
                }
            "$endpoint/${minioOssProperties.bucketName}/$sanitizedPath"
        }
}
